package com.ruoyi.framework.security.dingtalk;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

import java.util.Collection;

/**
 * 钉钉登录身份认证令牌
 *
 * @author xueyu
 */
@Slf4j
@Setter
public class DingTalkAuthenticationToken extends AbstractAuthenticationToken {

    private static final long serialVersionUID = 4749318097616220787L;

    /**
     * 未登录之前 表示用户的登录名称
     * 登录之后 代表已经认证过了的用户信息
     */
    private Object principal;

    /**
     * 凭证 密码凭证
     * 代表用户用于认证的凭证信息，用于验证用户的身份
     */
    private Object credentials;

    /**
     * 未认证的构造函数
     *
     * @param principal   用户信息
     * @param credentials 凭证信息
     */
    public DingTalkAuthenticationToken(Object principal, Object credentials) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        this.setAuthenticated(false);
    }

    /**
     * 已认证的构造函数
     *
     * @param principal   认证了的用户信息
     * @param credentials 凭证
     * @param authorities 权限集合
     */
    public DingTalkAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        super.setAuthenticated(true);
    }


    /**
     * 构建一个未认证的令牌身份
     *
     * @param principal   用户信息
     * @param credentials 凭证信息
     */
    public static DingTalkAuthenticationToken unauthenticated(Object principal, Object credentials) {
        return new DingTalkAuthenticationToken(principal, credentials);
    }

    /**
     * 构建一个已经认证了的令牌身份
     *
     * @param principal   认证了的用户信息
     * @param credentials 凭证
     * @param authorities 权限集合
     */
    public static DingTalkAuthenticationToken authenticated(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        return new DingTalkAuthenticationToken(principal, credentials, authorities);
    }

    /**
     * 赋值 是否认证  该类不允许直接调用这个方法进行已认证操作
     * 必须通过构造函数设置已认证!
     *
     * @param isAuthenticated 是否认证
     */
    @Override
    public void setAuthenticated(boolean isAuthenticated) {
        Assert.isTrue(!isAuthenticated, "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        super.setAuthenticated(false);
    }

    @Override
    public Object getCredentials() {
        return this.credentials;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
        this.credentials = null;
    }

}
